<template>
  <view class="page">
    <view class="container">
      <!-- 顶部返回按钮 -->
      <view class="back-btn" @click="goToMine">
        <image class="back-icon" src="@/static/icons/pageReturn.svg" mode="aspectFit"></image>
      </view>

      <!-- 标题 -->
      <view class="title">密码登录</view>

      <!-- 输入框区域 -->
      <view class="input-area">
        <input
            type="text"
            class="input-field"
            placeholder="+86 请输入手机号"
            v-model="formData.phone"
        />

        <!-- 密码输入框 -->
        <view class="password-input">
          <input
              type="text"
              class="input-field"
              placeholder="请输入密码"
              v-model="displayPassword"
              @input="handlePasswordInput"
          />
          <view class="eye-icon-button" @tap="togglePasswordVisibility">
            <view class="eye-icon-inner">
              <image
                  class="eye-icon"
                  :src="showPassword ? '/static/icons/eye_open.svg' : '/static/icons/eye_close.svg'"
                  mode="aspectFit"
              ></image>
            </view>
          </view>
        </view>

        <view class="login-links">
          <text class="forget-pwd" @click="goToForgetPassword">忘记密码</text>
          <view class="register-btn" @click="goToRegister">
            <text>新用户注册</text>
            <image class="right-arrow" src="@/static/icons/normalReturn.svg" mode="aspectFit"></image>
          </view>
        </view>

        <button
            class="submit-btn"
            :class="{ active: canSubmit }"
            :disabled="!canSubmit"
            @click="handleLogin"
        >
          登录
        </button>
      </view>

      <!-- 切换登录方式 -->
      <view class="divider">
        <view class="line"></view>
        <text class="text">验证码登录</text>
        <view class="line"></view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import userApi from '@/http/models/user';

const showPassword = ref(false);

// 实际密码存储
const realPassword = ref('');

// 显示用密码
const displayPassword = ref('');

// 表单数据
const formData = ref({
  phone: '',
  password: ''
});

// 监听真实密码变化，更新显示密码
watch(realPassword, (newVal) => {
  if (showPassword.value) {
    displayPassword.value = newVal; // 显示真实密码
  } else {
    displayPassword.value = '*'.repeat(newVal.length); // 显示*号
  }
});

// 处理密码输入
const handlePasswordInput = () => {
  if (showPassword.value) {
    // 如果显示真实密码，用户输入的是真实密码
    realPassword.value = displayPassword.value;
  } else {
    // 如果显示*号，根据输入长度更新真实密码
    const inputLength = displayPassword.value.length;
    const currentLength = realPassword.value.length;

    if (inputLength > currentLength) {
      // 用户输入了新字符
      realPassword.value += displayPassword.value.slice(-1);
    } else if (inputLength < currentLength) {
      // 用户删除了字符
      realPassword.value = realPassword.value.slice(0, -1);
    }
  }
  formData.value.password = realPassword.value;
};

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;

  if (showPassword.value) {
    // 显示真实密码
    displayPassword.value = realPassword.value;
  } else {
    // 显示*号
    displayPassword.value = '*'.repeat(realPassword.value.length);
  }
};

// 计算属性：手机号是否有效
const isPhoneValid = computed(() => {
  return /^1[3-9]\d{9}$/.test(formData.value.phone);
});

// 计算属性：是否可以提交表单
const canSubmit = computed(() => {
  return (
      isPhoneValid.value &&
      realPassword.value.length >= 6
  );
});

// 跳转到我的页
const goToMine = () => {
  uni.switchTab({
    url: '/pages/mine/mine'
  });
};

// 跳转到注册页面
const goToRegister = () => {
  uni.navigateTo({
    url: '/pages/login/register'
  });
};

// 跳转到忘记密码页面
const goToForgetPassword = () => {
  uni.navigateTo({
    url: '/pages/login/forgot-password'
  });
};

// 处理登录
const handleLogin = async () => {
  try {
    const res = await userApi.login({
      phone: formData.value.phone,
      password: realPassword.value
    });

    if (res.code === 200) {
      uni.setStorageSync('token', res.data.token);
      uni.setStorageSync('userInfo', res.data.user);
      await uni.showToast({title: '登录成功', icon: 'success'});
      setTimeout(() => {
        uni.switchTab({url: '/pages/mine/mine'});
      }, 1500);
    } else {
      await uni.showToast({title: res.msg || '登录失败', icon: 'none'});
    }
  } catch (error) {
    console.error('登录失败:', error);
    uni.showToast({ title: '登录失败，请稍后重试', icon: 'none' });
  }
};
</script>

<style scoped>
@import '../../components/scss/login-common.css';

.login-links {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin: 10px 0 30px;
  font-size: 14px;
}

.forget-pwd {
  color: #667eea;
  cursor: pointer;
}

.register-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #667eea;
  cursor: pointer;
}

.right-arrow {
  width: 12px;
  height: 12px;
  transform: rotate(180deg);
}
</style>